<template>
    <el-menu
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="horizontal"
            @select="handleSelect"
            router
    >
        <el-menu-item index="/">首页</el-menu-item>

        <div class="flex-grow"/>

        <el-menu-item index="login" v-show="showLoginMenu">登陆</el-menu-item>
        <el-menu-item v-show="showLoginMenu" index="register">注册</el-menu-item>
        <el-menu-item v-show="showExitMenu" index="exit">退出</el-menu-item>
        <el-menu-item v-show="showExitMenu" index="editPassword">修改密码</el-menu-item>

    </el-menu>
</template>

<script lang="ts" setup>
    import {onBeforeUnmount, ref} from 'vue'
    import {useRouter} from 'vue-router'
    import {Local} from "@/utils/local";
    import emitter from "@/utils/event-bus";
    import {MittEventEnum} from "@/utils/enum/mitt-event-enum"
    import {LoginStateEnum} from "@/utils/enum/enum"


    const router = useRouter()


    let showExitMenu = ref(false);//是否显式退出菜单
    let showLoginMenu = ref(true);//是否显式登陆菜单
    //
    if (Local.getToken()) {
        showLoginMenu.value = false;
        showExitMenu.value = true;
    }
    let activeIndex = ref("/")
    if (Local.getMenuIndex()) {
        //获取当前项目连接
        if (window.location.hash == "#/" && Local.getMenuIndex() != "1") {
            activeIndex = ref("/")
            Local.setMenuIndex("/")
        } else {
            activeIndex = ref(Local.getMenuIndex())
        }
    } else {
        activeIndex = ref("/")
    }

    const handleSelect = (key: string, keyPath: string[]) => {
        activeIndex.value = key;
        Local.setMenuIndex(key)
        if (key == "/") {
            router.push({name: "home"})
        } else if (key == "exit") {
            Local.removeToken();
            showExitMenu.value = false;
            showLoginMenu.value = true;
            router.push({name: "home"})
        } else if (key == "editPassword") {
            console.log(">>>>>>>>>>修改密码")
            router.push({name: "editPassword"})
        }
    }

    emitter.on(MittEventEnum.LOGIN_STATE_EVENT, (info) => {
        if (info == LoginStateEnum.LOGINED) {
            activeIndex.value = "/";
            showExitMenu.value = true;
            showLoginMenu.value = false;
        } else if (info == LoginStateEnum.EXIT_OR_OVERDUE_TOKEN) {
            activeIndex.value = "/";
            showExitMenu.value = false;
            showLoginMenu.value = true;
        }
    });

    onBeforeUnmount(() => {
        emitter.off(MittEventEnum.LOGIN_STATE_EVENT)
    })

</script>
<style scoped>
    .flex-grow {
        flex-grow: 0.95;
    }

    a {
        text-decoration: none;
    }
</style>